import Vue from 'vue'

export default {
	install: function (Vue) {
		// 输入框点击后，选中文字
		Vue.directive('selectTextOnFocus', {
			bind: function (el, binding) {
				function bindDom(el) {
					if (el.tagName !== 'INPUT') {
						;[...el.children].forEach(dom => {
							bindDom(dom)
						})
					} else {
						el.onfocus = function () {
							setTimeout(() => {
								el.select()
							}, 30)
						}
						return true
					}
				}

				bindDom(el)
			},
		})
		// 自动聚焦
		Vue.directive('focus', {
			inserted: function (el, value) {
				value = value == 'undefined' ? true : value
				if (value) {
					el.focus()
				}
			},
		})



		// 防止重复提交
		Vue.directive('noMoreClick', {
			inserted(el, binding) {
				el.addEventListener('click', e => {
					let time = 3000
					let value = el.innerText
					if (Number(binding.arg) > 3000) {
						time = Number(binding.arg)
					}
					let countdown = time / 1000
					el.disabled = true
					// setTimeout(() => {
					// 	el.disabled = false
					// }, time)
					let timeLimit = setInterval(() => {
						countdown--
						// el.innerText = `${countdown} 秒后可重新点击`
						el.classList.add('BtnDisabled')
						if (countdown == 0) {
							// el.innerText = value
							el.disabled = false
							el.classList.remove("BtnDisabled");
							clearInterval(timeLimit)
						}
					}, 1000)
				})
			},
		})

		Vue.directive('onClickaway', {
			// 初始化指令  
			bind(el, binding, vnode) {
				function documentHandler(e) {
					// 这里判断点击的元素是否是本身，是本身，则返回  
					if (el.contains(e.target)) {
						return false;
					}
					// 判断指令中是否绑定了函数  
					if (binding.expression) {
						// 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法  
						binding.value(binding.arg);
					}
				}
				// 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听  
				el.__vueClickOutside__ = documentHandler;
				document.addEventListener('click', documentHandler);
			},
			update() { },
			unbind(el, binding) {
				// 解除事件监听  
				document.removeEventListener('click', el.__vueClickOutside__);
				delete el.__vueClickOutside__;
			},
		})
	},
}
